package org.ims.inv.web.action.worklog;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.ims.inv.model.system.ModelAppDictionary;
import org.ims.inv.model.system.ModelAppProjectGroup;
import org.ims.inv.model.system.ModelAppUser;
import org.ims.inv.model.worklog.ModelWorkBaseLog;
import org.ims.inv.model.worklog.ModelWorkDailyLog;
import org.ims.inv.model.worklog.ModelWorkWeeklyLog;
import org.ims.inv.service.project.ServiceProject;
import org.ims.inv.service.worklog.ServiceWorkDailyLog;
import org.ims.inv.service.worklog.ServiceWorkWeeklyLog;
import org.ims.inv.vo.VoWorkLog;
import org.ims.inv.web.action.BaseAppAction;
import org.ims.inv.web.util.ContextUtil;
import org.ims.inv.web.util.ExcelTemplateSupport;

import cn.trymore.core.exception.ServiceException;
import cn.trymore.core.util.UtilCollection;
import cn.trymore.core.util.UtilDate;
import cn.trymore.core.util.UtilResources;
import cn.trymore.core.util.UtilString;
import cn.trymore.core.vo.VoTplExcelObj;
import cn.trymore.core.web.paging.PaginationSupport;
import cn.trymore.core.web.paging.PagingBean;

/**
 * Action: 工作日志
 * 
 * @author Jeccy.Zhao
 *
 */
public class WorkLogAction
extends BaseAppAction
{
	/**
	 * The LOGGER
	 */
	private static final Logger LOGGER = Logger.getLogger(WorkLogAction.class);
	
	/**
	 * Service of daily worklog
	 */
	protected ServiceWorkDailyLog serviceWorkDailyLog;
	
	/**
	 * Service of weekly worklog
	 */
	protected ServiceWorkWeeklyLog serviceWorkWeeklyLog;
	
	/**
	 * Service of project
	 */
	protected ServiceProject serviceProject;
	
	/**
	 * The file upload destination path.
	 */
	private String uploadPath = "";
	
	/**
	 * The file upload temporary path.
	 */
	private String tempPath = "";
	
	/**
	 * 初始化日期请求
	 * 
	 * @param request
	 * @throws Exception 
	 */
	private void initDateQuery (HttpServletRequest request) throws Exception
	{
		int currentWeekNum = UtilDate.getWeekNumber();
		int maxWeekNum = UtilDate.getMaxWeekNumOfYear();
		
		Date currentDate = new Date();
		
		int paramWeek = currentWeekNum;
		if (request.getParameter("week") != null)
		{
			paramWeek = Integer.valueOf(request.getParameter("week"));
		}
		else if (request.getParameter("date") != null)
		{
			paramWeek = Integer.valueOf(UtilDate.getWeekNumber(
					UtilDate.toDate(request.getParameter("date"))));
			
			currentDate = UtilDate.toDate(request.getParameter("date"));
		}
		else
		{
			paramWeek = Integer.valueOf(UtilDate.getWeekNumber(currentDate));
		}
		
		int year = UtilDate.getCurrentYear(currentDate);
		
		if (paramWeek > maxWeekNum)
		{
			paramWeek = 1;
			year = year + 1;
		}
		
		if (paramWeek < 1)
		{
			year = year - 1;
			paramWeek = UtilDate.getMaxWeekNumOfYear(year);
		}
		
		if (paramWeek == 1 && UtilDate.parseTime(currentDate).contains("-12-"))
		{
			year = year + 1;
		}
		
		if (request.getParameter("week") != null)
		{
			currentDate = UtilDate.getFirstDayOfWeek(year, paramWeek);
		}
		
		request.setAttribute("maxWeekNum", maxWeekNum);
		request.setAttribute("weekNum", currentWeekNum);
		request.setAttribute("startDate", UtilDate.getFirstDayOfWeek(year, paramWeek));
		request.setAttribute("endDate", UtilDate.getLastDayOfWeek(year, paramWeek));
		request.setAttribute("weekParam", paramWeek);
		request.setAttribute("wholeDates", UtilDate.getWholeWeekDate(year, paramWeek));
		request.setAttribute("currentDate", currentDate);
		request.setAttribute("nowDate", UtilDate.parseTime(new Date(), "yyyy-MM-dd"));
	}
	
	/**
	 * 根据工作日志类型转换为对应的状态值
	 * @param category
	 * @return
	 */
	private Integer convertToCategoryInt (String category)
	{
		if (UtilString.isNotEmpty(category))
		{
			if (category.equals(ModelWorkBaseLog.EWrokLogCategory.PERSONAL.getText()))
			{
				return ModelWorkBaseLog.EWrokLogCategory.PERSONAL.getValue();
			}
			
			if (category.equals(ModelWorkBaseLog.EWrokLogCategory.DEPARTMENT.getText()))
			{
				return ModelWorkBaseLog.EWrokLogCategory.DEPARTMENT.getValue();
			}
		}
		
		return null;
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 我的日志 & 部门日志 记录页面
	 */
	public ActionForward pageWorkLogIndex (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			Integer category = this.convertToCategoryInt(request.getParameter("cat"));
			if (category == null)
			{
				return ajaxPrint(response, 
						getErrorCallback("数据加载失败: 未知工作日志类型"));
			}
			
			// 初始化日期/周请求
			initDateQuery(request);
			
			String date = request.getParameter("date");
			if (!UtilString.isNotEmpty(date))
			{
				if (request.getAttribute("currentDate") != null)
				{
					date = UtilDate.parseTime((Date)request.getAttribute("currentDate"));
				}
				else
				{
					date = UtilDate.parseTime(new Date());
				}
			}
			
			// 查询每天日志
			List<ModelWorkDailyLog> dailyLogs = 
					this.serviceWorkDailyLog.getWeekDailyLogByDate(date, category);
			
			if (dailyLogs != null)
			{
				Map<String, List<ModelWorkDailyLog>> hashDailyLog = new HashMap<String, List<ModelWorkDailyLog>>();
				for (ModelWorkDailyLog dailyLog : dailyLogs)
				{
					String dailyLogDate = UtilDate.parseTime(dailyLog.getLogDate(), "yyyy-MM-dd");
					if (!hashDailyLog.containsKey(dailyLogDate))
					{
						hashDailyLog.put(dailyLogDate, new ArrayList<ModelWorkDailyLog>());
					}
					
					hashDailyLog.get(dailyLogDate).add(dailyLog);
				}
				
				request.setAttribute("logData", hashDailyLog);
			}
			
			// 查询周总结日志
			request.setAttribute("weekLog", this.getWorkWeeklyLogByDate(
				(Date)request.getAttribute("startDate"), 
				(Date)request.getAttribute("endDate"),
				category
			));
			
			this.outWriteAllParameters(request);
			
			return mapping.findForward("page.worklog.record.index");
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 部门日志查看
	 */
	public ActionForward pageWorkLogDepartmentOverview (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			initDateQuery(request);
			
			return mapping.findForward("page.worklog.dept.overview");
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * 
	 * @return
	 */
	private String getObservedUserIds ()
	{
		List<String> userIds = new ArrayList<String>();
		
		try
		{
			List<ModelAppUser> userManager = this.serviceAppUser.findByUserRole("ROLE_PROJECT_MANAGER");
			if (userManager != null)
			{
				for (ModelAppUser user : userManager)
				{
					if (!user.isSuperUser() && user.getUserStatus().equals(ModelAppUser.STAT_NORMAL))
					{
						if (!userIds.contains(user.getId()))
						{
							userIds.add(user.getId());
						}
					}
				}
			}
			
			List<ModelAppUser> userMaster = this.serviceAppUser.findByUserRole("ROLE_PROJECT_MASTER");
			if (userManager != null)
			{
				for (ModelAppUser user : userMaster)
				{
					if (!user.isSuperUser() && user.getUserStatus().equals(ModelAppUser.STAT_NORMAL))
					{
						if (!userIds.contains(user.getId()))
						{
							userIds.add(user.getId());
						}
					}
				}
			}
			
			List<ModelAppUser> userAssistant = this.serviceAppUser.findByUserRole("ROLE_PROJECT_ASSISTANT");
			if (userManager != null)
			{
				for (ModelAppUser user : userAssistant)
				{
					if (!user.isSuperUser() && user.getUserStatus().equals(ModelAppUser.STAT_NORMAL))
					{
						if (!userIds.contains(user.getId()))
						{
							userIds.add(user.getId());
						}
					}
				}
			}
		}
		catch (Exception e)
		{
			
		}
		
		return UtilString.join(userIds, ",");
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 成员日志查看
	 */
	public ActionForward pageWorkLogMemberOverview (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			initDateQuery(request);
			
			String[] userIds = null;
			
			if (ContextUtil.getCurrentUser().isAssistant())
			{
				// 项目部秘书可以看到所有项目成员的工作日志
				String allUserIds = this.getObservedUserIds();
				if (UtilString.isNotEmpty(allUserIds))
				{
					userIds = allUserIds.split(",");
				}
			}
			else
			{
				// 获取所带的项目组
				ModelAppProjectGroup criteria = new ModelAppProjectGroup();
				criteria.setGroupLeaderIds(ContextUtil.getCurrentUser().getId());
				List<ModelAppProjectGroup> myGroups = this.serviceAppProjectGroup.getByCriterion(criteria);
				
				if (!UtilCollection.isNotEmpty(myGroups))
				{
					// 没带任何项目, 只显示自己的工作日志
					userIds = new String[]{ContextUtil.getCurrentUser().getId()};
					request.setAttribute("singleTeam", true);
				}
				else
				{
					// 获取项目成员ID集合
					Set<String> members = new HashSet<String>();
					for (ModelAppProjectGroup group : myGroups)
					{
						String[] memberIds = group.getGroupMemberIds().split(",");
						for (String memberId : memberIds)
						{
							members.add(memberId);
						}
						
						String[] leaderIds = group.getGroupLeaderIds().split(",");
						for (String leaderId : leaderIds)
						{
							members.add(leaderId);
						}
					}
					
					userIds = new String[members.size()];
					userIds = members.toArray(userIds);
				}
			}
			
			// 根据用户ID集合查询日志
			List<ModelWorkDailyLog> dailyLogs = this.serviceWorkDailyLog.getWeekDailyLogByUsers(
				UtilDate.parseTime((Date)request.getAttribute("startDate"), "yyyy-MM-dd"), 
				UtilDate.parseTime((Date)request.getAttribute("endDate"),  "yyyy-MM-dd"), userIds);
			
			Map<String, Map<String, Boolean>> userFlags = new HashMap<String, Map<String,Boolean>>();
			if (dailyLogs != null)
			{
				for (ModelWorkDailyLog dailyLog : dailyLogs)
				{
					String logUserId = dailyLog.getLogOwner().getId();
					String logDate = UtilDate.parseTime(dailyLog.getLogDate(), "yyyy-MM-dd");
					
					if (!userFlags.containsKey(logUserId))
					{
						userFlags.put(logUserId, new HashMap<String, Boolean>());
					}
					
					if (!userFlags.get(logUserId).containsKey(logDate))
					{
						userFlags.get(logUserId).put(logDate, true);
					}
				}
			}
			
			request.setAttribute("userFlags", userFlags);
			request.setAttribute("users", this.serviceAppUser.findByUserIDs(userIds));
			
			return mapping.findForward("page.worklog.member.overview");
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	
	/**
	 * 根据查询条件获取分页日志数据
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	private PaginationSupport<ModelWorkDailyLog> getPagingWorkLogByQuery (
			final HttpServletRequest request, final PagingBean pagingBean) throws Exception
	{
		Integer category = this.convertToCategoryInt(request.getParameter("cat"));
		if (category == null)
		{
			throw new Exception("未知工作日志类型");
		}
		
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		
		if (!UtilString.isNotEmpty(startDate, endDate))
		{
			Date nowDate = new Date();
			startDate = UtilDate.parseTime(UtilDate.getFirstDayOfWeek(nowDate), "yyyy-MM-dd");
			endDate = UtilDate.parseTime(UtilDate.getLastDayOfWeek(nowDate), "yyyy-MM-dd");
			
			request.setAttribute("startDate", startDate);
			request.setAttribute("endDate", endDate);
		}
		
		String logOwnerId = request.getParameter("uid");
		if (!UtilString.isNotEmpty(logOwnerId))
		{
			if (category.equals(ModelWorkBaseLog.EWrokLogCategory.PERSONAL.getValue()))
			{
				logOwnerId = ContextUtil.getCurrentUser().getId();
				request.setAttribute("uid", logOwnerId);
			}
		}
		
		// 设置查询请求实体
		ModelWorkDailyLog criterion = new ModelWorkDailyLog();
		criterion.setLogCategory(category);
		if (UtilString.isNotEmpty(logOwnerId))
		{
			ModelAppUser logOwner = this.serviceAppUser.get(logOwnerId);
			criterion.setLogOwner(logOwner);
			request.setAttribute("logOwner", logOwner);
		}
		
		String workTypeId = request.getParameter("workType");
		if (UtilString.isNotEmpty(workTypeId))
		{
			ModelAppDictionary workType = new ModelAppDictionary();
			workType.setId(workTypeId);
			criterion.setLogWorkType(workType);
		}
		
		return this.serviceWorkDailyLog.getPaginationDailyLogByRangeDate(startDate, endDate, criterion, pagingBean);
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 日志查询
	 */
	public ActionForward dialogWorkLogQuery (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			PagingBean pagingBean = this.getPagingBean(request);
			PaginationSupport<ModelWorkDailyLog> pagingData = this.getPagingWorkLogByQuery(request, pagingBean);
			
			// request.setAttribute("datagrid", pagingData); 
			this.outWriteAllParameters(request);
			this.outWritePagination(request, pagingBean, pagingData);
			
			if (pagingData != null)
			{
				Map<String, List<ModelWorkDailyLog>> hashDailyLog = new TreeMap<String, List<ModelWorkDailyLog>>();
				for (ModelWorkDailyLog dailyLog : pagingData.getItems())
				{
					String dailyLogDate = UtilDate.parseTime(dailyLog.getLogDate(), "yyyy-MM-dd");
					if (!hashDailyLog.containsKey(dailyLogDate))
					{
						hashDailyLog.put(dailyLogDate, new ArrayList<ModelWorkDailyLog>());
					}
					
					hashDailyLog.get(dailyLogDate).add(dailyLog);
				}
				
				request.setAttribute("logData", hashDailyLog);
			}
			
			// 查询工作类型
			request.setAttribute("dictWorkTypes", this.getDictionariesByType("DICT_WORKLOG_TYPE"));
								
			
			return mapping.findForward("dialog.worklog.query");
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 日志维护(Daily)
	 */
	public ActionForward dialogWorkDailyLogMaintenance (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			this.outWriteAllParameters(request);
			
			Integer category = this.convertToCategoryInt(request.getParameter("cat"));
			if (category == null)
			{
				return ajaxPrint(response, 
						getErrorCallback("数据加载失败: 未知工作日志类型"));
			}
			
			// 查询工作类型
			request.setAttribute("dictWorkTypes", 
					this.getDictionariesByType("DICT_WORKLOG_TYPE"));
			
			// 查询当天个人日志
			request.setAttribute("dailyLogs", 
					this.getWorkDailyLogByDate(request.getParameter("date"), category));
			
			return mapping.findForward("dialog.worklog.daily.maintenance");
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * 获取周总结日志
	 * 
	 * @param startDate
	 * @param endDate
	 * @param category
	 * @return
	 * @throws ServiceException
	 */
	private ModelWorkWeeklyLog getWorkWeeklyLogByDate (
			Date startDate, Date endDate, Integer category) throws ServiceException
	{
		ModelWorkWeeklyLog criterion = new ModelWorkWeeklyLog();
		criterion.setStartDate(startDate);
		criterion.setEndDate(endDate);
		criterion.setLogCategory(category);
		
		if (ModelWorkBaseLog.EWrokLogCategory.PERSONAL.getValue().equals(category))
		{
			criterion.setLogOwner(ContextUtil.getCurrentUser());
		}
		
		List<ModelWorkWeeklyLog> result = this.serviceWorkWeeklyLog.getByCriterion(criterion);
		if (result != null && result.size() > 0)
		{
			return result.get(0);
		}
		
		return null;
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 日志维护(Weekly)
	 */
	public ActionForward dialogWorkWeeklyLogMaintenance (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			this.outWriteAllParameters(request);
			
			Integer category = this.convertToCategoryInt(request.getParameter("cat"));
			if (category == null)
			{
				return ajaxPrint(response, 
						getErrorCallback("数据加载失败: 未知工作日志类型"));
			}
			
			Date startDate = UtilDate.toDate(request.getParameter("startDate"));
			Date endDate = UtilDate.toDate(request.getParameter("endDate"));
			
			request.setAttribute("entity", 
					getWorkWeeklyLogByDate(startDate, endDate, category));
			
			return mapping.findForward("dialog.worklog.weekly.maintenance");
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * 获取日期所登记的工作事件
	 * 
	 * @param date
	 * @param category
	 * @return
	 * @throws Exception
	 */
	private List<ModelWorkDailyLog> getWorkDailyLogByDate (String date, Integer category) throws Exception
	{
		ModelWorkDailyLog criteria = new ModelWorkDailyLog();
		criteria.setLogDate(UtilDate.toDate(date));
		
		if (ModelWorkBaseLog.EWrokLogCategory.PERSONAL.getValue().equals(category))
		{
			criteria.setLogOwner(ContextUtil.getCurrentUser());
		}
		
		criteria.setLogCategory(category);
		
		return serviceWorkDailyLog.getByCriterion(criteria);
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 日志保存(Daily)
	 */
	public ActionForward actionSaveWorkDailyLog (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			Integer category = this.convertToCategoryInt(request.getParameter("cat"));
			if (category == null)
			{
				return ajaxPrint(response, 
						getErrorCallback("数据加载失败: 未知工作日志类型"));
			}
			
			// 获取参数组值
			Map<String, Map<String, String>> logInputs = 
					this.getGroupedRequestParameters(request, new String[] {"pobj"});
			
			if (logInputs != null)
			{
				String paramLogDate = request.getParameter("logDate");
				if (UtilString.isNotEmpty(paramLogDate))
				{
					Date logDate = UtilDate.toDate(request.getParameter("logDate"));
					
					// 获取日期所拥有的工作事件
					List<ModelWorkDailyLog> dailyLogs = 
							this.getWorkDailyLogByDate(request.getParameter("logDate"), category);
					
					Map<String, List<ModelWorkDailyLog>> loggedProjects = new HashMap<String, List<ModelWorkDailyLog>>();
					if (dailyLogs != null)
					{
						for (ModelWorkDailyLog dailyLog : dailyLogs)
						{
							if (dailyLog.getLogProject() != null)
							{
								String projectId = dailyLog.getLogProject().getId();
								if (!loggedProjects.containsKey(projectId))
								{
									loggedProjects.put(projectId, new ArrayList<ModelWorkDailyLog>());
								}
								
								loggedProjects.get(projectId).add(dailyLog);
							}
						}
					}
					
					List<String> entityIds = new ArrayList<String>();
					for (Map<String, String> input : logInputs.values())
					{
						// 获取页面参数输入
						String projectId = input.get("id");
						String eventText = input.get("event");
						String workType = input.get("workType");
						String projectName = input.get("projectName");
						
						if (!UtilString.isNotEmpty(eventText))
						{
							continue;
						}
						
						ModelWorkDailyLog entity = null;
						//if (UtilString.isNotEmpty(projectName, projectId))
						//{
							boolean isNewEntity = true;
							if (input.containsKey("logId") && UtilString.isNotEmpty(input.get("logId")))
							{
								// 更新项目日志
								entity = this.serviceWorkDailyLog.get(input.get("logId"));
								entity.setLogEvent(eventText);
								
								if (UtilString.isNotEmpty(projectId, projectName))
								{
									entity.setLogProject(serviceProject.get(projectId));
								}
								else
								{
									entity.setLogProject(null);
								}
								
								
								isNewEntity = false;
								entityIds.add(input.get("logId"));
							}
							else if (UtilString.isNotEmpty(projectId) && loggedProjects.containsKey(projectId))
							{
								boolean isExisted = false;
								for (List<ModelWorkDailyLog> dailyLogList : loggedProjects.values())
								{
									if (isExisted)
									{
										break;
									}
									
									for (ModelWorkDailyLog dailyLog : dailyLogList)
									{
										if (dailyLog.getLogWorkType().getId().equals(workType))
										{
											entity = dailyLog;
											isExisted = true;
											break;
										}
									}
								}
								
								// 存在同样的项目及工作类型, 进行事件合并及更新日志
								entity.setLogEvent(entity.getLogEvent() + "," + eventText);
								isNewEntity = false;
							}
							
							if (isNewEntity)
							{
								// 全新的项目工作事件
								entity = new ModelWorkDailyLog();
								entity.setLogRecorder(ContextUtil.getCurrentUser());
								entity.setLogDate(logDate);
								entity.setLogCategory(category);
								
								if (category.equals(ModelWorkBaseLog.EWrokLogCategory.PERSONAL.getValue()))
								{
									entity.setLogOwner(ContextUtil.getCurrentUser());
								}
								
								entity.setLogStatus(1);
								entity.setLogEvent(eventText);
								
								if (UtilString.isNotEmpty(projectId))
								{
									entity.setLogProject(serviceProject.get(projectId));
								}
								else
								{
									entity.setLogProject(null);
								}
							}
							
							entity.setLogWorkType(serviceAppDictionary.get(workType));
							
							this.serviceWorkDailyLog.save(entity);
						//}
					}
					
					// 删除被移除的工作事件
					for (List<ModelWorkDailyLog> dailyLogList : loggedProjects.values())
					{
						for (ModelWorkDailyLog dailyLog : dailyLogList)
						{
							if (!entityIds.contains(dailyLog.getId()))
							{
								this.serviceWorkDailyLog.remove(dailyLog);
							}
						}
					}
				}
				else
				{
					return ajaxPrint(response, getErrorCallback("数据加载失败,原因: 日志日期参数未传入.."));
				}
			}
			
			return ajaxPrint(response, 
					getSuccessCallback("日志提交成功.", CALLBACK_TYPE_CLOSE, CURRENT_NAVTABID, null, false));
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * 初始化文件夹
	 */
	private void initFolders ()
	{
		this.uploadPath = UtilResources.getWebRootPath() + "uploads";
		
		File localFile = new File(this.uploadPath);
		if (!localFile.exists())
		{
			localFile.mkdirs();
		}
		
		this.tempPath = this.uploadPath + "/temp";
		File tmpFile = new File(this.tempPath);
		if (!tmpFile.exists())
		{
			tmpFile.mkdirs();
		}
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 日志导出
	 */
	public ActionForward actionExportWorkLog (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			initFolders();
			
			PagingBean pagingBean = new PagingBean(1, 0);
			PaginationSupport<ModelWorkDailyLog> pagingData = this.getPagingWorkLogByQuery(request, pagingBean);
			
			if (pagingData != null && pagingData.getItemCount() > 0)
			{
				VoTplExcelObj obj = ExcelTemplateSupport.getTplObjFromTplFile(
						ExcelTemplateSupport.XLS_TPL_PATH + "/excel.worklog.xml", null);
				
				if (obj != null)
				{
					List<Map<String, Object>> data = new ArrayList<Map<String,Object>>();
					for (ModelWorkDailyLog workLog : pagingData.getItems())
					{
						VoWorkLog row = this.convertFromEntity(workLog);
						if (row != null)
						{
							Map<String, Object> singleRow = new HashMap<String, Object>();
							singleRow.put("workLog", row);
							data.add(singleRow);
						}
					}
					
					obj = ExcelTemplateSupport.fillTplData(obj, data, null);
					obj.setSheetName("工作日志");
					
					String fileName = "exportWorkLog_" + UtilDate.parseTime(new Date(), "yyyyMMddHHmmssSS") + ".xls";
					ExcelTemplateSupport.createExcel(this.tempPath + "/" + fileName, obj);
					
					return ajaxPrint(response, "{status:200, file:'" + "temp/" + fileName + "', name:'" + fileName + "'}");
				}
				else
				{
					return ajaxPrint(response, "{status:500, message:'文件导出失败.'}");
				}
			}
			else
			{
				return ajaxPrint(response, "{status:500, message:'没有可导出的数据.'}");
			}
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading page", e);
			return ajaxPrint(response, "{status:500, message:'文件导出失败.'}");
		}
	}
	
	/**
	 * 转换为Excel中的对象数据
	 * 
	 * @param entity
	 * @return
	 */
	private VoWorkLog convertFromEntity (ModelWorkDailyLog entity)
	{
		if (entity != null)
		{
			VoWorkLog workLog = new VoWorkLog();
			workLog.setLogDate(UtilDate.parseTime(entity.getLogDate(), "yyyy-MM-dd"));
			workLog.setLogProjectName(entity.getLogProject().getProjectName());
			workLog.setLogProjectNo(entity.getLogProject().getProjectNo());
			workLog.setLogWorkType(entity.getLogWorkType().getDictKey());
			workLog.setLogEvent(entity.getLogEvent());
			
			return workLog;
		}
		
		return null;
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 日志保存(Weekly)
	 */
	public ActionForward actionSaveWorkWeeklyLog (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String logEvent = request.getParameter("logEvent");
			String startDate = request.getParameter("startDate");
			String endDate = request.getParameter("endDate");
			String currentDate = request.getParameter("currentDate");
			
			Integer category = this.convertToCategoryInt(request.getParameter("cat"));
			if (category == null)
			{
				return ajaxPrint(response, 
						getErrorCallback("数据加载失败: 未知工作日志类型"));
			}
			
			if (UtilString.isNotEmpty(logEvent, startDate, endDate))
			{
				logEvent = logEvent.replaceAll("\\r\\n|\\r|\\n", "<br/>");
				
				ModelWorkWeeklyLog entity = null;
				
				String entityId = request.getParameter("id");
				if (this.isObjectIdValid(entityId))
				{
					entity = this.serviceWorkWeeklyLog.get(entityId);
					if (entity == null)
					{
						return ajaxPrint(response, getErrorCallback("数据实体不存在: " + entityId));
					}
				}
				else
				{
					entity = new ModelWorkWeeklyLog();
					entity.setStartDate(UtilDate.toDate(startDate));
					entity.setEndDate(UtilDate.toDate(endDate));
					entity.setLogOwner(ContextUtil.getCurrentUser());
					entity.setLogCategory(category);
					entity.setLogRecorder(ContextUtil.getCurrentUser());
					entity.setLogStatus(1);
				}
				
				entity.setLogEvent(logEvent);
				
				this.serviceWorkWeeklyLog.save(entity);
				
				return ajaxPrint(response, 
						getSuccessCallback("工作总结保存成功.", CALLBACK_TYPE_CLOSE, CURRENT_NAVTABID, null, "{'date':'" + currentDate + "'}", false));
			}
			else
			{
				return ajaxPrint(response, getErrorCallback("无效的表单输入.."));
			}
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	public ServiceWorkDailyLog getServiceWorkDailyLog()
	{
		return serviceWorkDailyLog;
	}

	public void setServiceWorkDailyLog(ServiceWorkDailyLog serviceWorkDailyLog)
	{
		this.serviceWorkDailyLog = serviceWorkDailyLog;
	}

	public ServiceWorkWeeklyLog getServiceWorkWeeklyLog()
	{
		return serviceWorkWeeklyLog;
	}

	public void setServiceWorkWeeklyLog(ServiceWorkWeeklyLog serviceWorkWeeklyLog)
	{
		this.serviceWorkWeeklyLog = serviceWorkWeeklyLog;
	}
	
	public static Logger getLogger()
	{
		return LOGGER;
	}

	public ServiceProject getServiceProject()
	{
		return serviceProject;
	}

	public void setServiceProject(ServiceProject serviceProject)
	{
		this.serviceProject = serviceProject;
	}
}